import React from 'react';
import AdvancedTable from 'components/advanced-table'
import financeAuditService from './finance-audit.service'
import {dealListTag, invoiceAmountChange, messages, queryCurrencyPrecision} from "share/common";
import { Popover, Select } from 'antd';
import moment from 'moment'
import selectorData from "share/selectorData";
import NumberRange from 'containers/financial-management/expense-view/component/number-range'
import {connect} from "react-redux";
import CostCenterSearchForm from "components/template/cost-center-search-form/cost-center-search-form";
import DepartmentPicker from "../wait-for-billing/new-billing/department-picker";
import openSlideFrame from "share/openSlideFrame";
import SlideLoanDetail from "containers/loan-billing/slide/slide-loan-detail";
import Department from 'components/template/department';
import { labelIds } from "../expense-view/component/func-component";
import constants from 'share/constants';

class FinanceAuditBorrow extends React.Component {

  state = {
    sort: ''
  };

  searchForm = [
    {
      id: 'formOIDs',
      component: 'MultiSelectorV2',
      label: messages('expense-14.key220')/*表单类型*/,
      props: {
        type: 'authority_form',
        params: { formType: 3001 },
        labelKey: 'formName',
        isShowSelectAll: true
      },
      parser: value => ({
        formOIDs: value ? value.map(item => item.formOID) : null
      }),
      JSONObjectFormatterParams: ['formName', 'formOID']
    },
    {
      id: 'submittedDate', label: messages('common.submit.date')/*提交日期*/,
      component: 'DateRangePicker',
      parser: value => ({
        startDate: value && value[0] ? moment(value[0])
          .format('YYYY-MM-DD 00:00:00') : null,
        endDate: value && value[1] ? moment(value[1])
          .format('YYYY-MM-DD 23:59:59') : null
      })
    },
    {
      id: 'searchCostCenterCommands', label: messages('expense-14.key221')/*成本中心*/,
      component: <CostCenterSearchForm title={messages('expense-14.key221')/*成本中心*/}/>,
      tagParser: value => messages('common.total.selected', { arg1: value.length })/*已选 {arg1} 条*/
    },
    {
      id: 'selectCompanyOIDs',
      label: messages('expense-14.key320')/*公司*/,
      component: 'Chooser',
      props: {
        type: 'auto_audit_add_company',
        labelKey: 'name',
        valueKey: 'companyOID',
        onlyNeed: 'companyOID',
        single: false,
      }
    },
    {
      id: 'departmentOids',
      label: messages('common.department')/*部门*/,
      component: <Department/>,
      parser: value => ({
        departmentOids: value ? value.map(item => item.departmentOID) : null
      }),
      tagParser: value => (value.map(item => item.title)
        .join(','))
    }, {
      id: 'approvalDate', label: messages('expense-14.key222')/*审批日期*/,
      component: 'DateRangePicker',
      parser: value => ({
        approvalStartDate: value && value[0] ? moment(value[0])
          .format('YYYY-MM-DD 00:00:00') : null,
        approvalEndDate: value && value[1] ? moment(value[1])
          .format('YYYY-MM-DD 23:59:59') : null
      })
    },
    {
      id: 'businessCode',
      component: 'Input',
      label: messages('common.document.code')/*单号*/,
    },
    {
      id: 'applicantOID', label: messages('expense-14.key223')/*员工*/,
      component: 'Selector',
      props: {
        placeholder: messages('common.please.input')/*请输入*/ + messages('expense-14.key224')/*申请人姓名/工号*/,
        type: 'user',
        selectorItem: {
          ...selectorData['user'],
          url: `/api/user/documents/review/search`,
          label: record => (`${record.employeeID}-${record.fullName}${(record.status !== 1001 ?
              (`（${record.status === 1002 ?
                  messages('expense-14.key225')/*待离职员工*/ :
                  messages('expense-14.key226')/*离职员工*/}）`
              ) :
              ''
          )}`)
        },
        searchIfKeywordIsNull: true
      },
    },
    {
      id: 'corporationOIDs', label: messages('expense-14.key227')/*法人实体*/,
      component: 'Chooser',
      props: {
        type: 'legal_entity',
        labelKey: 'entityName',
        valueKey: 'companyReceiptedOID',
        listKey: 'rows'
      },
      parser: value => ({
        corporationOIDs: value ? value.map(item => item.companyReceiptedOID) : null
      }),
      JSONObjectFormatterParams: ['entityName', 'companyReceiptedOID']
    },
    {
      id: 'totalAmount',
      label: messages('expense-14.key228')/*金额范围*/,
      component: <NumberRange/>,
      parser: value => ({
        minTotalAmount: value && value[0] ? value[0] : null,
        maxTotalAmount: value && value[1] ? value[1] : null
      }),
      tagParser: value => value && (value[0] || value[1]) && `${value[0] === 0 ? value[0] : value[0] || ''} ~ ${value[1] === 0 ? value[1] : value[1] || ''}`
    },
    {
      id: 'creditScore',
      label: messages('expense-14.key229')/*信用分范围*/,
      component: <NumberRange/>,
      parser: value => ({
        creditScoreFrom: value && value[0] ? value[0] : null,
        creditScoreTo: value && value[1] ? value[1] : null
      }),
      tagParser: value => value && (value[0] || value[1]) && `${value[0] === 0 ? value[0] : value[0] || ''} ~ ${value[1] === 0 ? value[1] : value[1] || ''}`
    },
    labelIds(7),
    {
      id: 'nodeOIDs',
      component: 'MultiSelectorV2',
      label: messages('expense-14.key230')/*节点名称*/,
      props: {
        type: 'billNodeName',
        params: { entityType: 3001, status: this.props.status || 'prending_audit' },
        labelKey: 'name',
        isShowSelectAll: true
      },
      parser: value => ({
        nodeOIDs: value && value.length ? value.map(item => item.key)
          .join(',')
          .split(',') : null
      })
    },
    {
      id: 'receiveStatus',
      label: messages('expense-1.key609')/*收单状态*/,
      component: (
        <Select allowClear placeholder={messages('expense-1.key604')/*请选择temp*/}
                style={{ width: '100%' }}>
          {constants.receiptOptions.map(item => <Option key={item.value}>{item.label}</Option>)}
        </Select>
      ),
      tagParser: value => value ? constants.receiptOptions.filter(item => item.value == value)[0].label : null
    },
    {
      id: 'financeReceiverOIDs',
      label: messages('expense-1.key632')/*收单人*/,
      component: 'Selector',
      props: {
        type: 'user',
        placeholder: messages('expense-14.key516')/*请输入工号/姓名/手机号/部门/邮箱/职位*/,
        selectorItem: {
          ...selectorData['user'],
          url: `/api/users/v3/search?status=all&roleType=TENANT`,
          label: record => (`${record.employeeID}-${record.fullName}${(record.status !== 1001 ?
              (`（${record.status === 1002 ?
                  messages('request-4.key9')/*待离职员工*/ :
                  messages('request-4.key10')/*离职员工*/}）`
              ) :
              ''
          )}`)
        }
      },
      parser: value => value ? { financeReceiverOIDs: [value] } : void 0,
    }
  ];

  columns = [{
    title: messages('common.user.id')/*工号*/, dataIndex: "employeeID", width: '10%'
  }, {
    title: messages('common.applicant')/*申请人*/, dataIndex: "applicantName", width: '10%'
  }, {
    title: messages('common.submit.date')/*提交日期*/, dataIndex: "submittedDate", width: 120, sorter: true,
    render: date => new Date(date).format('yyyy-MM-dd')
  }, {
    title: messages('expense-14.key231')/*单据类型*/, dataIndex: 'formName', width: '15%', sorter: true,
    render: formName => (
      <Popover content={formName}>
        {formName}
      </Popover>
      )
  }, {
    title: messages('expense-14.key232')/*申请单号*/, dataIndex: 'businessCode', width: '15%', sorter: true
  }, {
    title: messages('expense-14.key230')/*节点名称*/,
    dataIndex: 'nodeName',
    hide: true,
    render: value => value ? <Popover content={value} placement="topLeft">{value}</Popover> : ''
  }, {
    title: messages('common.currency')/*币种*/, dataIndex: "currencyCode", width: 72,
    render: text => text || this.props.companyConfiguration.currencyCode
  }, {
      title: messages('expense-14.key233')/*待支付金额*/, dataIndex: "paymentAmount",
    width: '10%', align: "right",
    render: (value,record) => this.duePay(value,record.currencyCode)
  }, {
    title: messages('expense-14.key234')/*凭证编号*/,
    dataIndex: "origDocumentSequence",
    render: value => {
      return <Popover content={value} placement="topLeft">{value}</Popover>
    }
  },
    {
      title: messages('expense-14.key517')/*单据公司*/,
      dataIndex: 'docCompanyName',
      width: 120,
      hide: true,
      render: value => {
        return <Popover content={value} placement="topLeft">{value || '-'}</Popover>;
      }
    },
    {
      title: messages('expense-14.key518')/*单据公司编码*/,
      dataIndex: 'docCompanyCode',
      width: 120,
      hide: true,
      render: value => {
        return <Popover content={value} placement="topLeft">{value || '-'}</Popover>;
      }
    },
    {
      title: messages('expense-1.key609')/*收单状态*/,
      dataIndex: 'receiveStatus',
      width: 120,
      hide: true,
      render: value => constants.getTextByValue(String(value + ''), 'receiptOptions', 'label'),
    },
    {
      title: messages('expense-14.key519')/*收单人*/,
      dataIndex: 'receiveBillUserName',
      width: 120,
      hide: true,
      render: value => {
        return <Popover content={value} placement="topLeft">{value || '-'}</Popover>;
      }
    }
  ];

  componentDidMount() {
    const { onRef } = this.props;
    onRef && onRef(this);
  }

  duePay = (value,currencyCode) => {
    let text = this.filterMoney(value,queryCurrencyPrecision(currencyCode));
    return (<Popover content={text}>{text}</Popover>)
  };

  service = (page, pageSize, searchParams) => {
    const { status } = this.props;
    const { sort } = this.state;
    let params = { status, ...searchParams };
    return financeAuditService.getAuditBorrowList(page, pageSize, sort, params)
  };

  onChangeTable = (pagination, filters, sorter) => {
    const { sort } = this.state;
    let nextSort = '';
    if(sorter.order) {
      nextSort = `${sorter.columnKey},${sorter.order === 'ascend' ? 'ASC' : 'DESC'}`
    }
    if(nextSort !== sort) {
      this.setState({ sort: nextSort }, this.advancedTableRef.getList);
    }
  };

  handleRowClick = record => {
    const { status, pathname } = this.props;
    openSlideFrame.openLoanReport({
      formOID: record.formOID,
      loanBillOID: record.loanBillOid,
      pathname: pathname +'/'+ status,
      entry: 'audit',
    }, {
      noPadding: true,
      content: SlideLoanDetail,
      afterClose: value => typeof value === 'boolean' && value && this.advancedTableRef.getList()
    }, this);
  };

  render() {
    const { status } = this.props;
    return (
      <AdvancedTable
        index
        expandAll
        title={status === 'prending_audit' ? messages('expense-14.key235')/*【借款单】待审核*/ : messages('expense-14.key236')/*【借款单】已审核*/}
        searchForm={this.searchForm}
        columns={this.columns}
        service={this.service}
        onChange={this.onChangeTable}
        onRef={ref => this.advancedTableRef = ref}
        expandedRowRender={dealListTag}
        waterMark={true}
        rowKey={record => record.loanBillOid}
        onRow={record => ({
          onClick: () => this.handleRowClick(record)
        })}
        pinnedList={['submittedDate', 'approvalDate', 'businessCode']}
        tableName={`finance-audit.borrow.${status}`}
      />
    );
  }
}

function mapStateToProps(state) {
  return {
    companyConfiguration: state.login.companyConfiguration
  }
}

export default connect(mapStateToProps)(FinanceAuditBorrow)
